package revontuli.aMHD.datamanagement;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import revontuli.aMHD.dataclasses.Line;

public class LineXMLHandler extends DefaultHandler {
	private StringBuffer buffer = new StringBuffer();
	private ArrayList<Line> lineList;
	private Line line;
	private Line.LineStop stop;
	
	@Override
	public void startElement(String namespaceURI, String localName, String qName, Attributes atts) {
		buffer.setLength(0);
		
		if (localName.equals("linelist")) {
			lineList = new ArrayList<Line>();
		} else if (localName.equals("line")) {
			line = new Line(Integer.parseInt(atts.getValue("line_id")));
		} else if (localName.equals("stoplist")) {
			line.stops = new ArrayList<Line.LineStop>();
		} else if (localName.equals("stop")) {
			stop = line.new LineStop(Integer.parseInt(atts.getValue("stop_order")));
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName) {
		if (localName.equals("line")) {
			lineList.add(line);
		} else if (localName.equals("line_name")) {
			line.name = buffer.toString();
		} else if (localName.equals("direction")) {
			line.direction = Integer.parseInt(buffer.toString());
		} else if (localName.equals("vehicle")) {
			line.vehicle = Integer.parseInt(buffer.toString());
		} else if (localName.equals("active")) {
			line.active = (buffer.toString()=="0")?false:true;
		} else if (localName.equals("line_revision")) {
			line.line_revision = Integer.parseInt(buffer.toString());
		} else if (localName.equals("exceptional_ind")) {
			line.exceptional_ind = buffer.toString();
		} else if (localName.equals("exceptional_desc")) {
			line.exceptional_desc = buffer.toString();
		} else if (localName.equals("stop")) {
			line.stops.add(stop);
		} else if (localName.equals("stop_id")) {
			stop.id = Integer.parseInt(buffer.toString());
		} else if (localName.equals("platform_id")) {
			stop.platform = Integer.parseInt(buffer.toString());
		} else if (localName.equals("distance_time")) {
			stop.distance_time = Integer.parseInt(buffer.toString());
		}
	}
	
	@Override
	public void characters(char[] ch, int start, int length) {
		buffer.append(ch, start, length);
	}
	
	public ArrayList<Line> retrieveLineList() {
		return lineList;
	}
}
